package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.service.ImageHelper;
import com.landinfo.web.rest.util.CheckUploadFileUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ziqilv on 2017/7/21.
 * 文件上传
 */
@RestController
@RequestMapping("/api")
public class UploadFileResource {

    private final Logger log = LoggerFactory.getLogger(UploadFileResource.class);

    @Autowired
    private HttpServletRequest request;

    /**
     * 文件上传具体实现方法;
     *
     * @param file
     * @return
     */
    @PostMapping("/image/upload")
    @Timed
    public String shapeFileUpload(@RequestParam MultipartFile file) {
        log.debug("upload start");
        if (!file.isEmpty()) {
            try {
                String oldFileName = file.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString() + oldFileName.substring(oldFileName.lastIndexOf("."));
                String path = this.getApplicationPath();
                File tempFile = new File(path);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                File newFile = new File(path + newFileName);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                return newFileName;
                //return ImageHelper.fileToBase64(newFile.getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
        } else {
            return "上传失败，因为文件是空的.";
        }
    }

    @GetMapping("/image/icons")
    @Timed
    public List<String> getAllIcon() {
        ArrayList<String> fileNames = new ArrayList<>();
        String path = this.getApplicationPath();
        File tempFile = new File(path);
        if (tempFile.exists()) {
            File[] files = tempFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                fileNames.add(files[i].getName());
            }
        }
        return fileNames;
    }

    // 上传首页相关文件
    @PostMapping("/upload/homeImg")
    public String uploadLandFile(@RequestParam MultipartFile file, @RequestParam String type) {
        JSONObject result = saveFile(file, "homeFile", type, null, true);
        return JSON.toJSONString(result);
    }

    private JSONObject saveFile(MultipartFile file, String bigType, String smallType, String folder, Boolean returnOldName) {
        JSONObject result = new JSONObject();
        result.put("success", false);
        if (file == null) {
            result.put("msg", "上传文件是空的");
            return result;
        }
        try {
            long size = file.getSize() / 1024;
            String oldFileName = file.getOriginalFilename();
            if (!CheckUploadFileUtil.checkFileType(oldFileName)) {
                result.put("msg", "不能上传该类格式文件");
                return result;
            }
            String timeFormat1 = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String newFileName = timeFormat1 + oldFileName.substring(oldFileName.lastIndexOf("."));
//            String timeFormat = new SimpleDateFormat("yyyyMM").format(new Date());

            String path = this.getApplicationRootPath();
            String folderPath = "attached" + File.separator + bigType;  // 相对路径，返回结果用
            if (smallType != null && !"".equals(smallType)) {
                folderPath = folderPath + File.separator + smallType;
            }
            if (folder != null && !"".equals(folder)) {
                folderPath = folderPath + File.separator + folder;
            }
            File tempFile = new File(path + folderPath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            String filePath = path + folderPath + File.separator + newFileName;
            File newFile = new File(filePath);

            // 通过拷贝流的方式
            FileOutputStream out = new FileOutputStream(newFile);
            InputStream input =  file.getInputStream();
            IOUtils.copy(input, out);
            out.flush();
            out.close();

            String returnPath = folderPath + File.separator + newFileName;
            result.put("filePath", returnPath.replaceAll("\\\\", "/"));
            result.put("fileType", oldFileName.substring(oldFileName.lastIndexOf(".") + 1));
            if (returnOldName != null && returnOldName) {
                result.put("fileName", oldFileName);
            }
            result.put("size", size);
            result.replace("success", true);
            return result;
        } catch (IOException e) {
            result.put("msg", "上传失败！");
            return result;
        }
    }


    /**
     * 获取应用程序路径
     *
     * @return
     */
    private String getApplicationPath() {
        String rootPath = request.getSession().getServletContext().getRealPath("/") + File.separator + "attached" + File.separator + "icon" + File.separator;
        return rootPath;
    }

    /**
     * 获取应用程序根目录路径
     */
    private String getApplicationRootPath() {
        String rootPath = request.getSession().getServletContext().getRealPath("/") + File.separator;
        return rootPath;
    }
}
